<template>
  <div>
    <el-form label-width="160px">
      <el-form-item label="数据源" prop="connection">
        <el-popover
          ref="datasourceListPopover"
          placement="bottom-start"
          trigger="click"
          v-model="srcTablePopover">
          <flink-table-tree ref="datasourceListTree"
                      @tableSelectHandler="tableSelectHandler"
                      style="height: 400px; overflow-y: auto"></flink-table-tree>
          <el-input v-model="srcTableName" slot="reference" :readonly="true" placeholder="点击选择数据源"></el-input>
        </el-popover>
      </el-form-item>
      <el-dialog :visible.sync="show" title="构建数据关联" :close-on-click-modal="false" @close="show = false" width="70%">
        <!--        <el-scrollbar ref="scroll" style="height: 310px; margin-bottom: 10px">-->
        <el-form label-width="100px">
          <el-form-item label="数据源" prop="connection">
            <el-popover
              ref="datasourceListPopover"
              placement="bottom-start"
              trigger="click"
              v-model="srcSelectVisible">
              <src-tree ref="srcTree" @nodeClick="srcNodeClick" :srcID="srcId" :mHeight="500"></src-tree>
              <el-input v-model="srcName" slot="reference" :readonly="true" placeholder="点击选择数据源"></el-input>
            </el-popover>
          </el-form-item>
          <!--          <el-form-item label="规则生成">-->
          <el-tabs v-model="activeTab" style="margin-left: 45px; margin-right: 45px">
            <el-tab-pane label="数据项" name="first">
              <el-row :gutter="15" style="padding-bottom: 20px">
                <el-col :span="6">
                  <el-input v-model="filterText" size="mini" placeholder="筛选" style="margin-bottom: 2px"></el-input>
                  <el-scrollbar ref="scroll" style="height: 370px" class="dialog-panel">
                    <el-tree
                      :data="tableList"
                      style="height: 340px"
                      v-loading="tableLoading"
                      @node-click="tableNodeClick"
                      :filter-node-method="filterNode"
                      ref="tableTree"
                      highlight-current>
                      <div class="custom-tree-node" slot-scope="{ node, data }">
              <span class="node-icon">
                <svg-icon icon-class="icon-table"></svg-icon>
              </span>
                        <span>
                {{ data.tableName }}
              </span>
                      </div>
                    </el-tree>
                  </el-scrollbar>
                </el-col>
                <el-col :span="6">
                  <el-checkbox v-model="allColumnSelected" @change="selectAllColumn" style="margin-bottom: 10px">全选</el-checkbox>
                  <el-scrollbar ref="scroll" style="height: 370px" class="dialog-panel">
                    <el-tree
                      :data="columnList"
                      style="height: 340px"
                      v-loading="columnLoading"
                      node-key="id"
                      ref="columnTree"
                      :default-checked-keys="columnCheckedList"
                      :check-on-click-node="true"
                      @check-change="columnCheckChange"
                      show-checkbox
                      highlight-current>
                      <div class="custom-tree-node" slot-scope="{ node, data }">
              <span>
                {{ data.fieldName }}
              </span>
                      </div>
                    </el-tree>
                  </el-scrollbar>
                </el-col>
                <el-col :span="12">
                  <el-checkbox v-model="useAlias" :true-label="1" :false-label="0" style="margin-bottom: 10px">别名</el-checkbox>
                  <div class="dialog-panel">
                    <dataset-target ref="datasetTarget" :domHeight="348" :destList="targetColumn"></dataset-target>
                  </div>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="规则定义" name="second">
              <el-table :data="ruleList" size="mini">
                <el-table-column
                  header-align="center"
                  align="center"
                  width="200"
                  label="字段">
                  <template slot-scope="scope">
                    <el-select
                      v-model="ruleList[scope.$index].tableColumn"
                      placeholder="选择字段"
                      size="mini"
                      clearable
                      filterable>
                      <el-option
                        v-for="col in targetColumn"
                        :key="col.id"
                        :label="col.columnTitle"
                        :value="col.tableColumn">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  header-align="center"
                  align="center"
                  label="操作符"
                  width="200"
                  size="mini">
                  <template slot-scope="scope">
                    <el-select v-model="ruleList[scope.$index].operate" clearable
                               @change="operateChange(ruleList[scope.$index].operate, ruleList[scope.$index])" size="mini">
                      <!--去除1：N  2021-03-14 -->
                      <!--<el-option label="1对N" value="ONE_TO_N"></el-option>-->
                      <el-option label="左联(LEFT JOIN)" value="LEFT JOIN"></el-option>
                      <el-option label="右联(RIGHT JOIN)" value="RIGHT JOIN"></el-option>
                      <el-option label="内联(INNER JOIN)" value="INNER JOIN"></el-option>
                      <el-option label="包含" value="LIKE"></el-option>
                      <el-option label="等于" value="="></el-option>
                      <el-option label="不等于" value="!="></el-option>
                      <el-option label="大于" value=">"></el-option>
                      <el-option label="小于" value="<"></el-option>
                      <el-option label="大于等于" value=">="></el-option>
                      <el-option label="小于等于" value="<="></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  header-align="center"
                  align="center"
                  width="200"
                  label="值">
                  <template slot-scope="scope">
                    <el-select
                      v-if="(ruleList[scope.$index].operate==='LEFT JOIN') || (ruleList[scope.$index].operate==='RIGHT JOIN') || (ruleList[scope.$index].operate==='INNER JOIN')"
                      v-model="ruleList[scope.$index].targetTableColumn"
                      placeholder="选择字段"
                      size="mini"
                      clearable
                      filterable>
                      <el-option
                        v-for="col in targetColumn"
                        :key="col.id"
                        :label="col.columnTitle"
                        :value="col.tableColumn">
                      </el-option>
                    </el-select>
                    <el-input v-else size="mini" maxlength="50" v-model="ruleList[scope.$index].value"></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  header-align="center"
                  align="center"
                  width="100"
                  label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" size="small" @click="deleteRuleRow(scope)">删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-row type="flex">
                <el-button class="el-table-add-row"  @click="addRuleRow()" icon="el-icon-plus"> 添加</el-button>
              </el-row>
            </el-tab-pane>
          </el-tabs>
          <!--          </el-form-item>-->
          <!--        </el-scrollbar>-->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="show=false" icon="el-icon-back">取消</el-button>
          <el-button type="primary" icon="el-icon-check" @click="showSQL">确定</el-button>
        </span>
      </el-dialog>
    </el-form>
<!--    <el-form-item label="构建SQL">-->
<!--      <el-button @click="show = true" type="primary" size="mini">构建数据关联</el-button>-->
<!--    </el-form-item>-->
  </div>
</template>

<script>
import srcTree from '../../../common/src/src-tree.vue'
import tableTree from '../../../table/table-tree.vue'
import API from '../../../../../api/index'
import FlinkTableTree from './flink-table-tree.vue'

export default {
  name: "flink-sql-design",
  components: {
    srcTree,
    // datasetTarget,
    tableTree,
    FlinkTableTree
  },
  data () {
    return {
      srcSelectVisible: false,
      srcId: '',
      srcName: '',
      tableList: [],
      tableName: '',
      tableCode: '',
      columnList: [],
      columnCheckedList: [],
      tableLoading: false,
      columnLoading: false,
      targetColumn: [],
      ruleList: [],
      ruleColumnList: [],
      useAlias: 0,
      allColumnSelected: false,
      filterText: '',
      show: false,
      isLoad: false, // 读取数据源时不刷新targetColumn
      srcTablePopover: false,
      srcTableName: '',
      activeTab: 'first'
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tableTree.filter(val)
    }
  },
  methods: {
    // 复杂sql
    init (form, name) {
      this.srcId = form.src
      this.srcTableName = name
      if (form.targetColumn && form.ruleList) {
        this.targetColumn = form.targetColumn
        this.isLoad = true
        for (let item of this.targetColumn) {
          item.id = item.columnId
        }
        this.ruleList = form.ruleList
        this.alias = form.alias
      }
    },
    // 简单选择表
    initTable (name, srcId) {
      this.srcId = srcId
      this.srcTableName = name
    },
    srcNodeClick (data, node) {
      if (node.isLeaf) {
        this.srcSelectVisible = false
        this.srcId = data.id
        this.srcName = data.name
        this.getTableList()
      }
    },
    getTableList () {
      this.tableList = []
      this.columnList = []
      this.allColumnSelected = false
      if (this.isLoad) {
        this.isLoad = false
      } else {
        this.targetColumn = []
        this.ruleList = []
      }
      this.tableLoading = true
      this.$http({
        url: this.$http.adornUrl(`/src/table/list`),
        method: 'get',
        params: this.$http.adornParams({
          srcId: this.srcId,
          page: 1,
          limit: 1000
        })
      }).then(({data}) => {
        this.tableLoading = false
        if (data && data.code === 0) {
          this.tableList = data.page.list
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    tableNodeClick (data, node) {
      this.tableName = data.tableName
      this.tableCode = data.tableCode
      this.getColumnList(data.id)
    },
    getColumnList (tableId) {
      this.columnCheckedList = []
      for (let item of this.targetColumn) {
        this.columnCheckedList.push(item.id)
      }
      this.columnLoading = true
      this.columnList = []
      this.allColumnSelected = false
      this.$http({
        url: this.$http.adornUrl(`/src/table/columnList/${tableId}`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        this.columnLoading = false
        if (data && data.code === 0) {
          this.columnList = data.list
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    columnCheckChange (nodeData, checked) {
      if (checked) {
        this.appendColumn(nodeData)
      } else {
        this.removeColumn(nodeData.id)
      }
    },
    appendColumn (data) {
      let index = this.targetColumn.findIndex(
        d => d.id === data.id
      )
      let item = {
        id: data.id,
        showType: 1,
        tableColumn: this.tableCode + '.' + data.fieldCode,
        tableName: this.tableCode,
        columnName: data.fieldCode,
        columnTitle: this.tableName + '.' + data.fieldName,
        columnId: data.id
      }
      if (index < 0) {
        this.targetColumn.push(item)
      } else {
        this.targetColumn[index] = item
      }
    },
    removeColumn (id) {
      const index = this.targetColumn.findIndex(
        d => d.id === id
      )
      this.targetColumn.splice(index, 1)
    },
    addRuleRow () {
      this.ruleList.push({
        tableColumn: '',
        operate: '',
        targetTableColumn: '',
        value: ''
      })
    },
    deleteRuleRow (val) {
      this.ruleList.splice(val.$index, 1)
    },
    operateChange (operate, row) {
      if (operate !== 'LEFT JOIN' && operate !== 'RIGHT JOIN' && operate !== 'INNER JOIN' && operate !== 'ONE_TO_N') {
        row.targetTableColumn = '定值'
      } else {
        row.targetTableColumn = ''
      }
    },
    tableSelectHandler (data, node) {
      let form = {
        src: node.parent.data.id,
        srcName: node.parent.data.name,
        schema: data.schema,
        tableName: data.name,
        srcTableName: data.schemaTableName
      }
      // 数据源ID
      let datasourceId = data.parentId
      // 数据表名称
      let tableName = data.name
      let schemaName = data.schema
      const that = this
      const id = data.id
      this.srcTableName = data.schemaTableName
      this.srcTablePopover = false
      // 根据表名称，获取表字段信息
      let vFlinkDataBasePostData = {
        id: datasourceId,
        tableName: tableName
      }
      this.$http({
        url: this.$http.adornFlinkUrl(`/database/getColumn`),
        method: 'get',
        params: this.$http.adornParams(vFlinkDataBasePostData,false)
      }).then(({data}) => {
        if (data && data.code === 200) {
          let list = data.data
          if (list.length > 0) {
            // let filelds = []
            // list.forEach(element => {
            //   filelds.push(element.name)
            // })
            //
            // let lSelectSql = 'select ' + filelds.join(',') + ' from ' + this.srcTableName;

            this.$emit('showSQL', list, form)
          } else {
            this.$emit('showSQL', null, form)
          }

        } else {
          this.$message.error(data.message)
        }
      })

      //
      // API.srcAPI.getInfo(data.parentId).then(({data}) => {
      //   if (data && data.code === 0) {
      //     if (data.entity && data.entity.dbSchema) {
      //       schemaName = data.entity.dbSchema
      //     }
      //     API.tableAPI.getTableFields(id).then(({data}) => {
      //       if (data && data.code === 0) {
      //         if (data.list.length > 0) {
      //           let filelds = []
      //           data.list.forEach(element => {
      //             filelds.push(element.fieldCode)
      //           })
      //           let params = {
      //             database: datasourceId,
      //             table: tableName,
      //             schema: schemaName,
      //             columns: filelds.join(',')
      //           }
      //           API.database.getSQL15s(params).then(res => {
      //             this.$emit('showSQL', res.data, form)
      //           }).catch(error => {
      //             const errorResultData = error.response.data
      //             that.$message({
      //               message: errorResultData.error.message,
      //               type: 'warning'
      //             })
      //             this.$emit('showSQL', '', form)
      //           })
      //         }
      //       }
      //     })
      //   }
      // })
      this.srcPopover = false
    },
    showSQL () {
      this.show = false
      this.srcTableName = this.srcName
      this.$http({
        url: this.$http.adornUrl(`/src/dataset/sql`),
        method: 'post',
        data: this.$http.adornData({
          'useAlias': this.useAlias,
          'extractList': this.ruleList,
          'destList': this.targetColumn
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          let form = {
            src: this.srcId,
            srcName: this.srcName,
            alias: this.useAlias,
            ruleList: this.ruleList,
            targetColumn: this.targetColumn
          }
          this.$emit('showSQL', data.selectSql, form)
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    selectAllColumn (checked) {
      let keys = []
      if (checked) {
        for (let i = 0; i < this.columnList.length; i++) {
          keys.push(this.columnList[i].id)
        }
      }
      this.$refs.columnTree.setCheckedKeys(keys, false)
    },
    filterNode (value, data) {
      if (!value) return true
      return data.tableName.toLowerCase().indexOf(value) !== -1 || data.tableCode.toUpperCase().indexOf(value) !== -1
    }
  }
}
</script>

<style scoped>

</style>
